﻿/*
* 作者:haojielyb
* 邮箱:haojielyb@qq.com
*/

using Furion;
using Furion.DependencyInjection;
using Furion.Logging;
using Lxb.Model;
using MqttModel;
using Newtonsoft.Json;
using SqlSugar;
using StackExchange.Redis;
using System;
using System.IO;
using System.Threading.Tasks;

namespace FaceMqttClient

{
    public class Kaoqin_logService : ITransient
    {
        private readonly ISugarQueryable<Kaoqin_log> repository; // 仓储对象：封装简单的CRUD
        private readonly ISugarQueryable<Users> users;
        private readonly ISugarQueryable<Ad> ads;
        private readonly ISqlSugarClient db; // 核心对象：拥有完整的SqlSugar全部功能
        private string path = AppDomain.CurrentDomain.BaseDirectory;

        public Kaoqin_logService(ISqlSugarClient db)
        {
    
            this.db = db;    // 推荐操作
            repository=db.Queryable<Kaoqin_log>();  
            users=db.Queryable<Users>(); 
            ads=db.Queryable<Ad>();
        }

        public Ad getAdbyid(int id) {
            return ads.Where(a => a.id == id).First();
        }
        /// <summary>
        /// 保存刷脸记录
        /// </summary>
        /// <param name="path"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        private  async Task SaveRecode(string msg, string path = "")
        {
            //Console.WriteLine("打卡");
         
            var rdsconn = App.GetService<ConnectionMultiplexer>();


            var rec = JsonConvert.DeserializeObject<Rec>(msg);
            //            logger.LogError();
            StringLoggingPart.Default().SetMessage($"{rec.info.personId}打卡 {rec.info.facesluiceId}").LogInformation();
            Kaoqin_log kl = new Kaoqin_log();
            kl.cdate = DateTime.Now;
            kl.time = DateTime.Now; //Convert.ToDateTime(rec.info.time);
            kl.datep = kl.time.ToString("yyyy/MM/dd");
            kl.timep = kl.time.ToString("H:mm:ss");
            kl.authority = "facedoor2";
            kl.name = rec.info.persionName;
            kl.Id = rec.info.customId.Trim();
            if (String.IsNullOrEmpty(kl.Id))
            {
                kl.Id = rec.info.personId;
            }
            kl.sn = rec.info.facesluiceId;
            kl.scor = Convert.ToDecimal(rec.info.similarity1);
            var redis = rdsconn.GetDatabase(0);
            if (redis.KeyExists(kl.sn))
            {
                var db = App.GetService<ISqlSugarClient>();
                var adve = db.Queryable<Device>().Where(x => x.SN == kl.sn).First();
                redis.StringSet(kl.sn, adve.address, TimeSpan.FromMinutes(10));

            }
            try
            {
                kl.addr = redis.StringGet(kl.sn);
            }
            catch (Exception)
            {
                // StringLoggingPart.Default().SetMessage($"{kl.sn}地址获取错误").LogInformation();
                Console.WriteLine("地址获取错误");
            }

            if (kl.addr == null)
            {
                //  StringLoggingPart.Default().SetMessage($"{kl.sn}地址获取为空").LogInformation();
                kl.addr = "  ";
            }
            kl.wxtz = 0;
            kl.state = 0;
            kl.io = 0;
            kl.UID = "";




            //try
            //{
            //    String dir = kl.time.ToString("yyMMdd");
            //    if (!Directory.Exists(path + dir))
            //    {
            //        Directory.CreateDirectory(path + dir);
            //    }

            //    string imgPath = $"{kl.Id}_{DateTime.Now.Ticks}.jpg";

            //    OthTool.Base64StringToImage(rec.info.pic.Substring(23), $@"{path}{dir}/{imgPath}");

            //    kl.photo = $"{dir}/{imgPath}";
            //    Console.WriteLine("文件保存");
            //}
            //catch (Exception exr)
            //{
            //    StringLoggingPart.Default().SetMessage($"文件保存失败：{exr.Message}").LogError();

            //}

            await AddAsync(kl);
        }

        /// <summary>
        /// remark
        /// </summary>
        /// <returns></returns>
        public async Task AddAsync(Kaoqin_log Kaoqin)
        {
            DateTime dts = DateTime.Now.AddMinutes(-3);
            int ct = repository.Where(kk => kk.cdate > dts && kk.Id == Kaoqin.Id).CountAsync().Result;
            if (ct > 2)
            {
                Kaoqin.state = 1;
            }
            int userid = Convert.ToInt32(Kaoqin.Id);
            try
            {
                var user = users.Where(u => u.user_id == userid).First();
                if (user != null)
                {

                    var dat = DateTime.Now.Date;
                    var ad= ads.Where(a => a.school == user.slname && a.stime <= dat && a.etime >= dat).First();
                    if(ad!=null)
                     Kaoqin.adid = ad.id;
                }

            }
            catch (Exception)
            {


            }

            await db.Insertable(Kaoqin).ExecuteCommandAsync();
        }
    }
}